package ip

import (
	"fmt"
	"gitee.com/injoyai/goutil/conv"
	"gitee.com/injoyai/goutil/net/http"
	"gitee.com/injoyai/goutil/string/logs/v1"
	"net"
	"strings"
	"time"
)

type IPv4 struct {
	Country string //CN HK
	IPv4    string
	Time    time.Time
}

func GetIPv4Segment(like ...string) (map[uint8]map[uint8]*IPv4, error) {
	url := "http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest"
	bs, err := http.GetBytes(url)
	if err != nil {
		return nil, err
	}
	m := make(map[uint8]map[uint8]*IPv4)
next:
	for _, v := range strings.Split(string(bs), "\n") {
		if len(v) > 0 && v[0] != '#' {
			list := strings.Split(v, "|")
			if len(list) == 7 && list[0] == "apnic" && list[1] != "*" && list[2] == "ipv4" {
				for _, k := range like {
					if !strings.Contains(v, k) {
						continue next
					}
				}
				co := conv.Int(list[4]) / 256
				num := conv.Uint32([]byte(net.ParseIP(list[3])[12:16]))
				for i := 0; i < co; i++ {
					num += uint32(256)
					bs := conv.Bytes(num)
					logs.Debug(list[3], bs)
					if _, ok := m[bs[0]]; !ok {
						m[bs[0]] = make(map[uint8]*IPv4)
					}
					m[bs[0]][bs[1]] = &IPv4{
						Country: list[1],
						IPv4:    fmt.Sprintf("%d.%d.%d.%d", bs[0], bs[1], bs[2], bs[3]),
						Time: func() time.Time {
							t, _ := time.Parse("20060102", list[5])
							return t
						}(),
					}
				}
			}
		}
	}
	return m, nil
}
